#include "Client.h"

ThreadGame::ThreadGame(Client* cli) : ClientThread(cli, "ThreadGame") {
	client = cli;
	ticks = 0;
	t = ((float)geGetTick()) / 1000.0;
	dt = 0.0;
}

void ThreadGame::run(){
	client->res.sun->position.x = client->cam->x + 0.0;
	client->res.sun->position.y = client->cam->y + 10000.0 * geCos(((float)client->getDayTicks() - 6000) * 2.0 * M_PI / 24000.0);
	client->res.sun->position.z = client->cam->z + 10000.0 * geSin(((float)client->getDayTicks() - 6000) * 2.0 * M_PI / 24000.0);
	u8 sun_ambient = 128 - std::max(0, std::min(96, abs(client->getDayTicks() - 12000) * 128 / 12000));
	SET_COLOR(client->res.sun->ambient, RGBA(sun_ambient, sun_ambient, sun_ambient, 255));

	if(client->getWorld()->getGameMode() == MULTI){
		client->getClientConnect()->SendPlayerPositionLook(client->getPlayer());
	}
	
	client->getPlayer()->setAnimationSpeed(fminf(1.0, 0.25 * geDistance2D(0.0, 0.0, client->getPlayer()->getPhysicState()->velocity.x, client->getPlayer()->getPhysicState()->velocity.y)));
	if(client->getPlayer()->getAnimationSpeed() < 0.3 && fabsf(geSin(client->getPlayer()->getAnimationTick() * 7.0)) > 0.05){
		if(fabsf(geSin((client->getPlayer()->getAnimationTick() + 0.01) * 7.0)) > fabsf(geSin(client->getPlayer()->getAnimationTick() * 7.0))){
			client->getPlayer()->setAnimationSpeed(-0.3);
		}else{
			client->getPlayer()->setAnimationSpeed(0.3);
		}
	}
	client->getPlayer()->Animate(dt);

	std::vector<Entity*>* entities = client->getWorld()->getEntities();
	for(u32 i=0; i<entities->size(); i++){
		Entity* e = entities->at(i);
		e->UpdateLocation();
		e->setAnimationSpeed(fminf(1.0, 0.25 * geDistance2D(0.0, 0.0, e->getVelocity().x, e->getVelocity().y)));
		if(e->getAnimationSpeed() < 0.3 && fabsf(geSin(e->getAnimationTick() * 7.0)) > 0.05){
			if(fabsf(geSin((e->getAnimationTick() + 0.01) * 7.0)) > fabsf(geSin(e->getAnimationTick() * 7.0))){
				e->setAnimationSpeed(-0.3);
			}else{
				e->setAnimationSpeed(0.3);
			}
		}
		e->Animate(dt);
		if(client->getWorld()->getGameMode() == SOLO){
			entities->at(i)->Update(t, dt);
			if(!entities->at(i)->hasMoved()){
				entities->at(i)->ResetForces();
			}
			entities->at(i)->setMoved(false);
		}
	}

	dt = ((float)geGetTick()) / 1000.0 - t;
	t += dt;
	/*
	client->setGameTicks(client->getGameTicks() + 1);
	client->setDayTicks(client->getDayTicks() + 1);
	ticks = geWaitTick(1000/20, ticks);
	*/
	static u32 last_tick = 0;
	if(geGetTick() - last_tick >= 1000 / 20){
		last_tick = geGetTick();
		client->setGameTicks(client->getGameTicks() + 1);
		client->setDayTicks(client->getDayTicks() + 1);
	}
	ticks = geWaitTick(1000/60, ticks);
}
